package me.shurufa.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.adapter.MyDigestAdapter;
import me.shurufa.event.EventObject;
import me.shurufa.implement.DigestLongClickListener;
import me.shurufa.model.Digest;
import me.shurufa.model.DigestListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.colordialog.ColorDialog;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.RecyclerViewUtils;

/**
 * 我的书摘列表Fragment
 * 复用DigestFragment布局
 * 修改部分为适配器和接口 其他不变
 *
 * @FileName: me.shurufa.fragments.MyDigestFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-02-04 22:22
 */
public class MyDigestFragment extends BaseListFragment implements DigestLongClickListener {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_refresh)
    PtrClassicFrameLayout ptrRefresh;

    MyDigestAdapter digestAdapter;
    ArrayList dataList;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private long menuId;
    private String menuTitle;
    private TextView menuTextView;

    public static MyDigestFragment newInstance(long menuId,String menuTitle) {
        MyDigestFragment fragment = new MyDigestFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_MENU_ID, menuId);
        args.putString(Constants.ARG_MENU_TITLE,menuTitle);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            menuId = getArguments().getLong(Constants.ARG_MENU_ID);
            menuTitle = getArguments().getString(Constants.ARG_MENU_TITLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_digest_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
//        初始化刷新
        setRefresh();
        dataList = new ArrayList();
        digestAdapter = new MyDigestAdapter(this,dataList,this);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(digestAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_menu_title,recyclerView,false);
        menuTextView = (TextView)headerView.findViewById(R.id.menu_title);

        if (!TextUtils.isEmpty(menuTitle)){
            menuTextView.setText(menuTitle);
            RecyclerViewUtils.setHeaderView(recyclerView, headerView);
        }
        recyclerView.addOnScrollListener(mOnScrollListener);
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        DigestListResponse resp = (DigestListResponse) response;
        if (isNew) {
            digestAdapter.clear();
        }
        digestAdapter.append(resp.data);
        digestAdapter.notifyDataSetChanged();
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, DigestListResponse.class);
    }

    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        },2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage=1;
        loadData(1);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.Loading, null);
            loadData(mPage);
        }
    };


    protected void loadData(final int page) {
        if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<DigestListResponse>(DigestListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("token",Global.currentUser.token);
                    params.put("menuId",menuId);
                    params.put("page",page);
                    return HttpUtil.post(API.GET_MY_DIGEST_BY_MENUID, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    endRefreshing();
                }

                @Override
                protected void onSuccess(DigestListResponse result) {
                    //没有更多数据 不能加载更多
                    if (result.data == null || result.data.length == 0) {
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                    } else {
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                        hasMore = true;
                        mPage++;
                        bindData(result, page == 1);
                    }
                }
            }.start();
        }
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh!=null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    public void onEventMainThread(EventObject object) {
        Digest digest = null;
        digest = object.getDigest();
        if (digest != null) {
            if (object.getEventAction().equals(Constants.ACTION_MODIFY_MY_DIGEST)) {

                long digestId = digest.id;
                for (int i = 0; i < dataList.size(); i++) {
                    if (digestId == ((Digest) dataList.get(i)).id) {
                        dataList.set(i, digest);
                        digestAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    @Override
    public void onDigestLongClick(View view, final Digest digest) {
        ColorDialog dialog = new ColorDialog(getActivity());
        dialog.setTitle(getString(R.string.delete_digest));
        dialog.setContentText(getString(R.string.make_sure_delete_digest));
        dialog.setPositiveListener(getString(R.string.ok), new ColorDialog.OnPositiveListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                dialog.dismiss();
                new RequestServerTask<BaseResponse>(BaseResponse.class,getActivity(),getString(R.string.commit_pls_wait)){
                    @Override
                    protected String requestServer() {
                        Map<String,Object> params = new HashMap<String, Object>();

                        params.put("token", Global.currentUser.token);
                        params.put("excerptId",digest.id);
                        return HttpUtil.post(API.REMOVE_DIGEST,params);
                    }

                    @Override
                    protected void onSuccess(BaseResponse result) {
                        if (result.success){
                            for (int i = 0; i < dataList.size(); i++) {
                                if (digest.id == ((Digest)dataList.get(i)).id){
                                    digestAdapter.remove(i);
                                }
                            }
                        }
                    }
                }.start();
            }
        })
                .setNegativeListener(getString(R.string.cancel), new ColorDialog.OnNegativeListener() {
                    @Override
                    public void onClick(ColorDialog dialog) {
                        dialog.dismiss();
                    }
                }).show();
    }
}
